package com.example.it_com.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.it_com.common.AlipayConfig;
import com.example.it_com.common.Result;
import com.example.it_com.entity.Recharge;
import com.example.it_com.entity.User;
import com.example.it_com.mapper.RechargeMapper;
import com.example.it_com.mapper.UserMapper;
import com.example.it_com.service.RechargeService;
import com.example.it_com.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private UserService userService;

    @Resource
    private AlipayConfig alipayConfig;

    // 支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    private static final String FORMAT = "JSON";

    private static final String CHARSET = "UTF-8";
    // 签名方式
    private static final String SIGN_TYPE = "RSA2";
    @Autowired
    private RechargeMapper rechargeMapper;
    @Autowired
    private UserMapper userMapper;

    //支付宝支付(根据rechargeId)
    @PostMapping("/pay")
    public void pay(String rechargeId, HttpServletResponse httpResponse) throws Exception {
        // 查询充值信息
        LambdaQueryWrapper<Recharge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Recharge::getRechargeId, rechargeId);

        Recharge recharge = rechargeService.getOne(queryWrapper);

        //判断是否存在
        if (recharge == null) {
            httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Recharge not found");
            return;
        }
        //判断是否已支付
        if (recharge.getStatus() == 1) {
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Recharge already paid");
            return;
        }



        // 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,
                alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(),
                FORMAT,
                CHARSET,
                alipayConfig.getAlipayPublicKey(),
                SIGN_TYPE);

        // 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        request.setReturnUrl("http://localhost:8081/#/myinfo"); // 支付后跳回原来


        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", recharge.getRechargeId()); // 我们自己生成的订单编号
        bizContent.put("total_amount", recharge.getPayAmount()); // 订单的总金额
        bizContent.put("subject", "Recharge"); // 支付的名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); // 固定配置

        request.setBizContent(bizContent.toJSONString());


        // 执行请求，拿到响应的结果，返回给浏览器（固定写法）
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();


    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSifnature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(), "utf-8");
            // 支付宝验签
            if (checkSifnature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));




                String tradeId =params.get("out_trade_no");//商户订单号 rechargeId
                // 将 String 类型的支付金额转换为 float 类型
                float payAmount = Float.parseFloat(params.get("buyer_pay_amount"));

                log.info(tradeId);

                //更新订单状态为已支付，设置支付信息
                LambdaUpdateWrapper<Recharge> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(Recharge::getRechargeId, tradeId);
                updateWrapper.set(Recharge::getStatus, 1);

                Recharge recharge = rechargeService.getOne(updateWrapper);
                rechargeMapper.update(recharge, updateWrapper);


                //更新用户余额

                //根据recharge的user_id查user表单
                LambdaUpdateWrapper<User> updateWrapperUser = new LambdaUpdateWrapper<>();
                updateWrapperUser.eq(User::getUserId, recharge.getUserId());
                User user = userService.getOne(updateWrapperUser);
                if (user != null) {
                    float newBalance = user.getBalance() + payAmount*100;
                    user.setBalance(newBalance);
                    userMapper.update(user, updateWrapperUser);


//                Orders orders =ordersService.selectByOrderNo(tradeNo);
//                orders.setstatus("已支付");
//                orders.setPayTime(gmtPayment);
//                orders.setPayNo(alipayTradeNo);
//                ordersService.updateById(orders);

                }
            }
        }
        return "success";
    }


    //创建recharge订单
    @PostMapping("/createRecharge")
    public Result<Recharge> createRecharge(Integer userId, Integer number) {
        log.info(userId.toString());
        log.info(number.toString());


        Recharge recharge = new Recharge();
        recharge.setUserId(userId);
        recharge.setNumber(number);
        recharge.setRechargeId(UUID.randomUUID().toString().replace("-", ""));
        recharge.setPayAmount((float) (number * 0.01));
        LocalDateTime time=LocalDateTime.now();

        recharge.setPayTime(time);
        recharge.setStatus(0);

        rechargeService.save(recharge);

        return Result.success(recharge, "创建充值订单成功");

    }

}
